using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Playables;

namespace IQIGame.Onigao.GamePlay
{
    public class DummyHideBehaviour : PlayableBehaviour
    {
        public int dummy;
        public bool onlyChild = true;

        private Transform dummyTrans;
        private List<GameObject> hideGo = new List<GameObject>();

        public override void ProcessFrame(Playable playable, FrameData info, object playerData)
        {
            if (playable.GetDuration() - playable.GetTime() < 0.01f)
            {
                this.Stop();
            }
            else if (this.dummy != 0 && this.dummyTrans == null && playerData is EntityDriver rDriver)
            {
                var rUnitView = BattleClientUtil.GetUnitViewByEntityDriver(rDriver);
                var rBindComp = rUnitView.GetComponent<BattleViewBindPointComponent>(ETComponentType.BattleViewBindPointComponent);
                this.dummyTrans = rBindComp.GetBindPoint(this.dummy);
                this.hideGo.Clear();
                if (this.dummyTrans)
                {
                    if (this.onlyChild)
                    {
                        foreach (Transform rTrans in this.dummyTrans)
                        {
                            var rGo = rTrans.gameObject;
                            if (rGo.activeInHierarchy)
                            {
                                this.hideGo.Add(rGo);
                                rGo.SetActive(false);
                            }
                        }
                    }
                    else
                    {
                        var rGo = this.dummyTrans.gameObject;
                        this.hideGo.Add(rGo);
                        rGo.SetActive(false);
                    }
                }
            }
        }

        public override void OnBehaviourPlay(Playable playable, FrameData info)
        {
        }

        public override void OnBehaviourPause(Playable playable, FrameData info)
        {
            this.Stop();
        }

        private void Stop()
        {
            if (this.dummyTrans)
            {
                for (int i = 0; i < this.hideGo.Count; i++)
                {
                    if (this.hideGo[i])
                    {
                        this.hideGo[i].SetActive(true);
                    }
                }
                this.hideGo.Clear();
                this.dummyTrans = null;
            }
        }
    }
}